package common

import (
	"context"
	"encoding/json"
	commonmodel "gitee.com/zxs-micro/zxs-micro-common/grpc/common/model"
	protocommon "gitee.com/zxs-micro/zxs-micro-common/grpc/protos/common"
	"gitee.com/zxs-micro/zxs-micro-common/utils"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/mem"
	"sync"
	//"zxs-micro/fuwufaxian/model"
)

var ls *LoadService

func NewLoadService() *LoadService {
	if ls == nil {
		ls = new(LoadService)
	}
	return ls
}

type LoadService struct {
	lock sync.Mutex
	//Fuwulist map[string]map[string]model.Fuwu
}

func (l *LoadService) Load(ctx context.Context, req *protocommon.ServerLoadReq) (*protocommon.ServerLoadsResp, error) {
	rm := new(commonmodel.LoadModel)
	cpus, err := cpu.Times(true)
	if err != nil {
		return nil, err
	}
	rm.Cpus = cpus
	//通过loadavg作为权重，交给gateway进行加权随机
	rm.LoadAvg = utils.CurrentLoad()
	vm, err := mem.VirtualMemory()
	if err != nil {
		return nil, err
	}
	rm.Mem = vm
	rm.Disk = make(map[string]*disk.UsageStat)
	parts, err := disk.Partitions(true)
	if err != nil {
		return nil, err
	}
	for _, v := range parts {
		di, _ := disk.Usage(v.Mountpoint)
		rm.Disk[v.Mountpoint] = di
	}
	bs, _ := json.Marshal(rm)
	return &protocommon.ServerLoadsResp{
		Loads: bs,
	}, nil
}
